<template>
	<view class="container u-flex u-col-center u-row-between">
		<view class="order-top u-flex u-col-center u-row-between">
			<view class="item" :class="{ on: navindex == index }" v-for="(item, index) in navList" :key="index" @click="changeNav(index)">
				{{ item }}
			</view>
		</view>
		<view class="order-bottom">
			<swiper class="swiper" :current="navindex" @change="swiperChange">
				<!-- 恢复5个swiper-item保持滑动效果 -->
				<swiper-item v-for="(navItem, tabIndex) in navList" :key="tabIndex">
					<view class="item">
						<scroll-view scroll-y="true" class="scroll-Y" @scrolltolower="getMore(tabIndex)">
							<!-- 根据tabIndex过滤显示对应的订单 -->
							<view class="order" v-for="(item, itemIndex) in getFilteredList(tabIndex)" :key="itemIndex" @click="$pageTo('/pages/index/orderDetail?id=' + item.id)">
								<view class="order-title u-flex u-col-center u-row-between">
									<view class="t">编号：{{ item.order_no }}</view>
									<view class="state">
										{{ statusMap[item.status] }}
									</view>
								</view>
								<view class="goods">
									<view class="i u-flex u-col-top u-row-between" v-for="(product, productIndex) in item.products" :key="productIndex">
										<view class="img">
											<image :src="http + product.image" mode="aspectFill"></image>
										</view>
										<view class="con">
											<view class="title u-line-1">
												{{ product.title }}
											</view>
											<view class="tips">
												<text v-for="(spec, specIndex) in product.sell_spec.split(',')" :key="specIndex">{{ spec }}</text>
												<text v-for="(mounting, mountIndex) in product.mountings_texts" :key="mountIndex">{{ mounting.title }}-{{ mounting.intro }}</text>
											</view>
										</view>
										<view class="r">
											<view class="price">{{ item.pay_price }}元</view>
											<view class="num">×{{ product.num }}</view>
										</view>
									</view>
								</view>
								<view class="total">
									合计：{{ item.order_price }}元
									<text>丨</text>
									实付：{{ item.pay_price }}元
								</view>
								<!-- 操作按钮 -->
								<view class="btns u-flex u-col-center u-row-right" v-if="item.status == 1">
									<view class="btn1 btn" @click.stop="closeOrder(item.id, itemIndex, tabIndex)">关闭订单</view>
								</view>
							</view>
							<!-- 空状态 -->
							<view class="nolist" v-if="getFilteredList(tabIndex).length === 0 && !loading[tabIndex]">
								<u-empty mode="order" iconSize="60" text="暂无订单"></u-empty>
							</view>
							<!-- 加载更多提示 -->
							<view class="load-more" v-if="getFilteredList(tabIndex).length > 0 && pages[tabIndex] < totalPages[tabIndex]">
								<u-loadmore status="loading" />
							</view>
							<!-- 没有更多数据 -->
							<view class="load-more" v-if="getFilteredList(tabIndex).length > 0 && pages[tabIndex] >= totalPages[tabIndex]">
								<u-loadmore status="nomore" />
							</view>
						</scroll-view>
					</view>
				</swiper-item>
			</swiper>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			navList: ['全部', '待支付', '待发货', '待收货', '已收货', '已关闭'],
			statusMap: ['', '待支付', '待发货', '待收货', '已收货', '已关闭'],
			statusFilters: ['', 1, 2, 3, 4, 5],
			navindex: 0,
			// 单一数据源存储所有订单
			allOrders: [],
			// 每个tab的加载状态
			pages: [1, 1, 1, 1, 1, 1],
			totalPages: [0, 0, 0, 0, 0, 0],
			loading: [false, false, false, false, false, false],
			loadedTabs: new Set(), // 记录已经加载过的tab

			http: this.$imgUrl
		};
	},
	onLoad() {
		my.setNavigationBar({
			frontColor: '#000',
			backgroundColor: '#fff'
		});
		if (!uni.getStorageSync('token')) {
			uni.switchTab({
				url: '/pages/index/index'
			});
			return;
		}
	},
	onShow() {
		this.resetData();
		// 初始加载第一个tab的数据
		this.loadTabData(0);
	},
	methods: {
		// 获取过滤后的列表
		getFilteredList(tabIndex) {
			if (tabIndex === 0) {
				return this.allOrders; // 全部订单
			}
			const targetStatus = this.statusFilters[tabIndex];
			return this.allOrders.filter((item) => item.status === targetStatus);
		},

		// 获取商品价格（处理配件价格）
		getProductPrice(product) {
			return product.price - (product.mountings_price || 0);
		},

		// 重置数据
		resetData() {
			this.pages = [1, 1, 1, 1, 1, 1];
			this.totalPages = [0, 0, 0, 0, 0, 0];
			this.loading = [false, false, false, false, false, false];
			this.allOrders = [];
			this.loadedTabs.clear();
		},

		// 加载指定tab的数据
		loadTabData(tabIndex) {
			// 如果已经加载过，不再重复加载
			if (this.loadedTabs.has(tabIndex) && this.allOrders.length > 0) {
				return;
			}

			this.pages[tabIndex] = 1;
			this.getList(tabIndex);
		},

		closeOrder(id, index, tabIndex) {
			uni.showModal({
				title: '温馨提示',
				content: '你要关闭订单吗?',
				success: (res) => {
					if (res.confirm) {
						this.$http
							.post('/api/sell_order/closeOrder', {
								id: id
							})
							.then((res) => {
								if (res.code == 1) {
									// 直接更新订单状态为已关闭
									const orderIndex = this.allOrders.findIndex((item) => item.id === id);
									if (orderIndex > -1) {
										this.$set(this.allOrders[orderIndex], 'status',5);
									}
									uni.showToast({
										title: '关闭成功',
										icon: 'none'
									});
								} else {
									uni.showToast({
										title: res.msg,
										icon: 'none'
									});
								}
							});
					}
				}
			});
		},

		// 加载更多
		getMore(tabIndex) {
			if (this.pages[tabIndex] < this.totalPages[tabIndex]) {
				this.pages[tabIndex]++;
				this.getList(tabIndex);
			}
		},

		// 获取列表数据
		getList(tabIndex) {
			this.loading[tabIndex] = true;

			this.$http
				.post('/api/sell_order/list', {
					page: this.pages[tabIndex],
					limit: 10,
					status: this.statusFilters[tabIndex]
				})
				.then((res) => {
					this.loading[tabIndex] = false;
					if (res.code == 1) {
						if (this.pages[tabIndex] === 1) {
							// 第一页，如果是全部tab就替换，其他tab就合并
							if (tabIndex === 0) {
								this.allOrders = res.data.list;
							} else {
								// 移除该状态的所有订单，然后添加新的
								const targetStatus = this.statusFilters[tabIndex];
								this.allOrders = this.allOrders.filter((item) => item.status !== targetStatus);
								this.allOrders = [...this.allOrders, ...res.data.list];
							}
						} else {
							// 追加数据
							this.allOrders = [...this.allOrders, ...res.data.list];
						}
						this.totalPages[tabIndex] = res.data.total_page;

						// 标记该tab已加载
						this.loadedTabs.add(tabIndex);
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				})
				.catch((err) => {
					this.loading[tabIndex] = false;
					console.error('加载订单列表失败:', err);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				});
		},

		changeNav(index) {
			if (this.navindex != index) {
				this.navindex = index;
				this.loadTabData(index);
			}
		},

		swiperChange(e) {
			const index = e.detail.current;
			this.navindex = index;
			this.loadTabData(index);
		}
	}
};
</script>

<style lang="less" scoped>
@color: #e31d21;

.container {
	width: 100vw;
	height: 100vh;
	flex-direction: column;

	.order-top {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		background: #fff;

		.item {
			flex: 1;
			text-align: center;
			font-size: 28rpx;
			color: #333;
		}

		.on {
			position: relative;
			color: @color;

			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				width: 40rpx;
				height: 6rpx;
				background-color: @color;
				border-radius: 3rpx;
				margin-left: -20rpx;
			}
		}
	}

	.order-bottom {
		flex: 1;
		height: 1rpx;
		width: 100%;

		.swiper {
			width: 100%;
			height: 100%;

			.item {
				width: 100%;
				height: 100%;

				.scroll-Y {
					width: 100%;
					height: 100%;
					padding: 30rpx;
					box-sizing: border-box;

					.order {
						background-color: #fff;
						padding: 20rpx;
						border-radius: 10rpx;
						margin-bottom: 30rpx;

						.info {
							background-color: #fbeedf;
							padding: 10rpx;
							font-size: 24rpx;
							color: @color;
							line-height: 30rpx;
							border-radius: 6rpx;
						}

						.btns {
							margin-top: 20rpx;
							border-top: 2rpx solid #eee;
							padding-top: 20rpx;

							.btn {
								width: 180rpx;
								height: 60rpx;
								line-height: 60rpx;
								text-align: center;
								font-size: 24rpx;
								border-radius: 30rpx;
								box-sizing: border-box;
							}

							.btn1 {
								border: 2rpx solid #eee;
								color: #666;
							}

							.btn2 {
								margin-left: 30rpx;
								background-color: @color;
								color: #fff;
							}
						}

						.total {
							text-align: right;
							font-size: 30rpx;
							font-weight: 600;
							height: 60rpx;
							line-height: 60rpx;
							color: #333;

							text {
								color: #eee;
								padding: 0 10rpx;
								font-weight: 400;
							}
						}

						.order-title {
							height: 60rpx;
							line-height: 60rpx;

							.t {
								font-size: 26rpx;
								color: #333;
							}

							.state {
								font-size: 24rpx;
								color: #999;
							}
						}

						.goods {
							.i {
								padding: 10rpx 0;

								.img {
									width: 75rpx;
									height: 121rpx;
									border-radius: 10rpx;
									overflow: hidden;

									image {
										width: 100%;
										height: 100%;
									}
								}

								.con {
									flex: 1;
									padding: 0 20rpx;
									width: 1rpx;

									.title {
										font-size: 28rpx;
										color: #333;
									}

									.tips {
										text {
											color: #999;
											font-size: 24rpx;
											margin: 10rpx 10rpx 0 0;
										}
									}
								}

								.r {
									text-align: right;

									.price {
										font-size: 24rpx;
										color: #666;
										height: 60rpx;
										line-height: 60rpx;
									}

									.num {
										font-size: 24rpx;
										color: #666;
									}
								}
							}
						}
					}

					.load-more {
						padding: 20rpx 0;
					}
				}
			}
		}
	}
}
</style>
